package com.df.bpm.utils.entityCreator;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

public class EntityCreatorDB {
    public static void main(String[] args) {

        String tableSchema = "dbo";//TODO 目标DB表的模态名称
        String tableName = "logs_clientNews";//TODO 目标DB表名称

        String sourceRootPath = "businessOverview/src/main/java";//TODO 本项目父级路径，通常固定

        List<Map<String, Object>> columns = new DatabaseConfig().getTableColumns(tableSchema, tableName);

        try {
            new EntityCreatorDB().createEntity(sourceRootPath,tableSchema,tableName,columns);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 在entity路径下创建文件
     * @param sourceRootPath 项目父级路径，通常是src/main/java
     * @param tableSchema DB模态名
     * @param entityName 实体类名称
     * @param columns DB表结构信息
     */
    public void createEntity(String sourceRootPath,String tableSchema,String entityName,List<Map<String, Object>> columns) throws Exception {
        // 获取包名
        String packageName = EntityCreatorDB.class.getPackage().getName();

        // 替换包名中的点号为文件路径分隔符
        String packagePath = packageName.replace('.', File.separatorChar);

        // 构建上级目录路径
        String parentPath = new File(packagePath).getParent();
        parentPath = new File(parentPath).getParent();//再上一级路径

        // 拼接entity包的路径
        String entityPath = parentPath + File.separator + "entity";
//        String entityPath = "../.." + File.separator + "entity";

        String newClassName= Character.toUpperCase(entityName.charAt(0)) + entityName.substring(1);
        String filePath = Paths.get(sourceRootPath, entityPath, newClassName+".java").toString();
//        String filePath = Paths.get( entityPath, newClassName+".java").toString();

        // 创建File对象
        File file = new File(filePath);

        // 检查entity目录是否存在
        if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
            if (file.createNewFile()) {
                System.out.println("文件创建: " + filePath);
                try (FileWriter writer = new FileWriter(file)) {
                    String Data=dataFormat(entityPath.replace(File.separatorChar,'.'),tableSchema,entityName,columns);
                    writer.write(Data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("文件已存在: " + filePath);
            }
        } else {
            System.out.println("路径无法创建: " + entityPath);
        }
    }

    /**
     * 数据内容整理
     * @param entityPath 包路径
     * @param tableSchema DB模态名
     * @param entityName 实体类名称
     * @param columns DB表结构信息
     * @return 整理好的实体类数据内容
     */
    public String dataFormat(String entityPath, String tableSchema, String entityName, List<Map<String, Object>> columns){
        String newClassName= Character.toUpperCase(entityName.charAt(0)) + entityName.substring(1);
        StringBuilder data= new StringBuilder("package " + entityPath + "; \n\n");
        data.append("import com.baomidou.mybatisplus.annotation.IdType;//标记主键时有用，例如@TableId(value = \"partIndex\", type = IdType.AUTO)\n")
                .append("import com.baomidou.mybatisplus.annotation.TableId;//标记主键时有用，例如@TableId(value = \"partIndex\", type = IdType.AUTO)\n")
                .append("import com.baomidou.mybatisplus.annotation.TableField;//标记敏感字字段名有用，例如@TableField(value = \"\\\"procedure\\\"\")\n")
                .append("import com.baomidou.mybatisplus.annotation.TableName;\n")
                .append("import com.fasterxml.jackson.annotation.JsonFormat;\n")
                .append("import lombok.Getter;\n")
                .append("import lombok.Setter;\n")
                .append("import lombok.ToString;\n")
                .append("import lombok.experimental.Accessors;\n")
                .append("import org.springframework.format.annotation.DateTimeFormat;\n\n");
        data.append("import java.io.Serializable;\n").append("import java.util.Date;\n\n");
        data.append("@TableName(\"").append(tableSchema).append(".").append(entityName).append("\")\n").append("@Getter\n").append("@Setter\n").append("@ToString\n").append("@Accessors(chain = true)\n");
        data.append("public class ").append(newClassName).append(" implements Serializable {\n\n\n");

        for (Map<String, Object> column : columns) {
            String dataType=""+column.get("DATA_TYPE");
            String jDataType;
            String colName=""+column.get("COLUMN_NAME");
            if(dataType.contains("date")){
                data.append("\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n");
                data.append("\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n");
                jDataType="Date";
            }else if(dataType.contains("varchar")){
                jDataType="String";
            }else if(dataType.contains("int")){
                jDataType="Integer";
            }else if(dataType.contains("float")){
                jDataType="double";
            }else{
                jDataType="String";
            }
            data.append("\tprivate ").append(jDataType).append(" ").append(colName).append(";//").append(dataType).append("\n\n");
        }

        data.append("\n}");
        return data.toString();
    }
}


